import logging

from beanie import SortDirection

from core.logger import log
from beanie.odm.operators.find.logical import Or
from db.models.users import UserDocument
from db.models.wx_user_model import WxUserModel
from typing import List

from db.mysql.users import Users
from utils.wechat_pad_tools import WeChatPadClient

async def create_wx_user(user: UserDocument):
    """
    插入单条用户数据到数据库
    :param user: 包含用户信息的字典
    :return: 插入结果
    """
    try:
        wx_cli = WeChatPadClient()

        # 获取所有设备
        devices = wx_cli.get_all_devices()
        for device in devices:
            device_id = device.get("deviceId")
            ext = await WxUserModel.exists(device_id = device_id)
            if not ext and device.get("status") == 1:
                new_wx_user = {
                    "user_id":user.user_id,
                    "device_id": device_id,
                    "nickname": device.get("deviceName"),
                    "auth_key":device.get("authKey"),
                    "status": device.get("status"),
                    "expire_time": device.get("expireTime")
                }
                wx_user_model = WxUserModel(**new_wx_user)
                await wx_user_model.insert()
        return 'ok'
    except Exception as e:
        print(f"插入失败: {e}")
        return None

async def create_rag_by_user_id(user_id: str,user_name: str):
    new_user = {
        "user_id": user_id,
        "device_id": f"rag_{user_name}",
        "auth_key": "123456",
        "nickname": f"rag_{user_name}",
        "status": 1,
    }
    wx_user = WxUserModel(**new_user)
    await wx_user.insert()

async def get_wx_user(user: Users, is_rag: bool = None):
    """
    查询所有 WxUserModel 实例（即数据库中的 wx_user 文档）
    :return: 用户对象列表
    """
    # logger.info("查询所有 WxUserModel 实例")
    try:
        query_conditions = []
        if user.username != 'admin':
            # 普通用户只能查看自己的用户
            query_conditions.append(WxUserModel.user_id == user.user_id)
        if is_rag is not None:
            query_conditions.append(WxUserModel.is_rag == is_rag)
        # 根据 user_id 过滤查询
        users = await WxUserModel.find(*query_conditions).sort(
            [("status", SortDirection.DESCENDING), ("nickname", SortDirection.ASCENDING)]
        ).to_list()
        return users
    except Exception as e:
        log.exception(f"查询失败: {e}")
        return []
async def get_wx_id_by_token_key(auth_key: str):
    """
    根据微信令牌 获取微信 ID
    :param token_key: 微信令牌
    :return: wx_id
    """
    try:
        user = await WxUserModel.find_one(WxUserModel.auth_key == auth_key)
        if user:
            return user.device_id
        return None
    except Exception as e:
        log.exception(f"查询失败: {e}")
        return None

async def get_wx_token_key(wx_id: str):
    """
    根据微信 ID 查询用户 TOKEN KEY
    :param wx_id: 微信 ID
    :return: TOKEN KEY
    """
    try:
        user = await WxUserModel.find_one(WxUserModel.wx_id == wx_id)
        if user:
            return user.token_key
        else:
            return None
    except Exception as e:
        print(f"查询失败: {e}")
        return None

async def update_wx_usr_status(auth_key: str, status: int):
    try:
        user = await WxUserModel.find_one(WxUserModel.auth_key == auth_key)
        if not user:
            print(f"未找到 auth_key 为 {auth_key} 的用户")
            return False

        if user.status != status:
            await user.set({WxUserModel.status: status})
            print("用户状态已更新")
        return True
    except Exception as e:
        print(f"更新失败: {e}")
        return False

async def update_monitor_status(auth_key: str, status: bool):
    try:
        user = await WxUserModel.find_one(WxUserModel.auth_key == auth_key)
        if not user:
            return False
        if user.is_active != status:
            await user.set({WxUserModel.is_active: status})
        return  True
    except Exception as e:
        return False

async def update_wx_user_id(device_id: str, user_id: str):
    try:
        wx_user = await WxUserModel.find_one(WxUserModel.device_id==device_id)
        if not wx_user:
            return False
        if wx_user.user_id != user_id:
            await wx_user.set({WxUserModel.user_id: user_id})
        return  True
    except Exception as e:
        return False

async def delete_wx_user(device_id: str):
    try:
        await WxUserModel.find_one(WxUserModel.device_id == device_id).delete()
        return True
    except Exception as e:
        return False